const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const fs = require('fs')
const multer = require('multer')

let mainWindow

// 配置文件处理
function loadConfig() {
    try {
        const configPath = path.join(__dirname, 'config.json');
        const configRaw = fs.readFileSync(configPath, 'utf8');
        const newConfig = JSON.parse(configRaw);
        
        // 验证必要的配置项
        if (!newConfig.staticFolder) {
            newConfig.staticFolder = 'public';
        }
        
        return {
            ...newConfig,
            staticFolder: path.isAbsolute(newConfig.staticFolder) 
                ? newConfig.staticFolder 
                : path.resolve(__dirname, newConfig.staticFolder),
            enableUpload: newConfig.enableUpload !== false
        };
    } catch (e) {
        console.error('Error loading config:', e);
        return null;
    }
}

// 初始加载
let config = loadConfig() || {
    enableUpload: false,
    staticFolder: path.join(__dirname, 'ggb')
};

// 如果需要热重载配置
fs.watchFile(path.join(__dirname, 'config.json'), () => {
    const newConfig = loadConfig();
    if (newConfig) {
        config = newConfig;
        console.log('Configuration reloaded');
    }
});

let ROOT_PATH 
if(app.isPackaged){
    if(config.staticFolder && config.staticFolder!=''){
        ROOT_PATH = config.staticFolder;
    }else{
        ROOT_PATH = app.getPath('exe')+"/ggb";
    }
}else{
    ROOT_PATH = app.getAppPath()+"/ggb";
}
console.log(ROOT_PATH)

// 文件列表处理
function getFileList(requestedPath = '') {
    // 安全检查
    if (requestedPath.includes('..')) {
        throw new Error('Invalid path specified')
    }

    const fullPath = path.join(ROOT_PATH, requestedPath)
    const stats = fs.statSync(fullPath)

    if (stats.isDirectory()) {
        const files = fs.readdirSync(fullPath, { withFileTypes: true })
        return files.map(file => {
            const filePath = path.join(fullPath, file.name)
            const fileStats = fs.statSync(filePath)
            const relativePath = path.join(requestedPath, file.name).replace(/\\/g, '/')
            
            return {
                name: file.name,
                type: file.isDirectory() ? 'directory' : 'file',
                path: file.isDirectory() ? relativePath : filePath,
                mtime: fileStats.mtime.toISOString()
            }
        })
    } else {
        const relativePath = requestedPath.replace(/\\/g, '/')
        return [{
            name: path.basename(fullPath),
            type: 'file',
            path: relativePath,
            mtime: stats.mtime.toISOString()
        }]
    }
}

// 文件上传处理
let uploadHandler = null
if (config.enableUpload) {
    const storage = multer.diskStorage({
        destination: (req, file, cb) => {
            const uploadPath = path.join(ROOT_PATH, 'upload')
            fs.mkdirSync(uploadPath, { recursive: true })
            cb(null, uploadPath)
        },
        filename: (req, file, cb) => {
            const decodedName = Buffer.from(file.originalname, 'latin1').toString('utf8')
            cb(null, decodedName)
        }
    })
    uploadHandler = multer({ storage }).single('file')
}

app.whenReady().then(() => {
    mainWindow = new BrowserWindow({
        width: 1200,
        height: 800,
        webPreferences: {
            nodeIntegration: false,  // 禁用nodeIntegration
            contextIsolation: true,  // 启用上下文隔离
            enableRemoteModule: false, // 禁用remote模块
            preload: path.join(__dirname, 'preload.js')  // 指定preload脚本
        }
    })

    // 加载本地HTML文件或远程URL
    mainWindow.loadFile('index.html')

    // 设置IPC通信
    ipcMain.handle('getFileList', (event, path) => {
        try {
            return { success: true, data: getFileList(path) }
        } catch (err) {
            console.error('Error getting file list:', err)
            const status = err.code === 'ENOENT' ? 404 : 500
            return { success: false, error: err.message, status }
        }
    })

    // 文件上传处理
    ipcMain.handle('uploadFile', (event, fileData) => {
        if (!config.enableUpload) {
            return { success: false, error: '文件上传功能已被禁用', status: 403 }
        }

        try {
            // 这里是简化的文件保存逻辑，实际应用中可能需要更复杂的处理
            const uploadPath = path.join(ROOT_PATH, 'upload')
            fs.mkdirSync(uploadPath, { recursive: true })
            const filePath = path.join(uploadPath, fileData.name)
            fs.writeFileSync(filePath, Buffer.from(fileData.data))
            
            return { 
                success: true, 
                message: 'File uploaded successfully',
                file: { 
                    path: uploadPath,
                    name: fileData.name
                } 
            }
        } catch (err) {
            return { success: false, error: err.message, status: 500 }
        }
    })
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
})
